package com.example.demo.opc;

import com.example.demo.opc.utils.OpcClient;
import com.example.demo.opc.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * https://blog.csdn.net/yhtppp/article/details/80680446
 * @Classname OpcClient
 * @Description TODO
 * @Date 2021/4/27 19:53
 * @Created by kkk
 */

@Component
public class OpcClientBean {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public  void start(String host, String user, String password, String domain,String clsid) {
        OpcClient opcClient = new OpcClient();
        // 1.显示server上的opc server应用列表
        opcClient.showAllOPCServer(host, user, password, domain);

        // 2.连接指定的opc server
        boolean ret = opcClient.connectServer(host, clsid, user, password, domain);
        if (!ret) {
            System.out.println("connect opc server fail");
            return;
        }
        // 3.检查opc server上的检测点
        List<String> itemIdList = new ArrayList<String>();
        itemIdList.add("tongdao2.shebei1.TAG5");
        itemIdList.add("tongdao2.shebei1.TAG1");
        ret = opcClient.checkItemList(itemIdList);
        if (!ret) {
            System.out.println("not contain item list");
            return;
        }

        // 4.注册回调
        opcClient.subscribe(new Observer() {
            @Override
            public void update(Observable observable, Object arg) {
                Result result = (Result) arg;
                System.out.println("update result=" + result);
            }
        });

        // 5.添加监听检测点的数据
        // client和server在不同网段，可以访问
        opcClient.syncReadObject("tongdao2.shebei1.TAG5", 3000);
        opcClient.syncReadObject("tongdao2.shebei1.TAG1", 2000);
        /**
         * TODO 问题
         * client和server在不同网段，访问失败，比如：server为10.1.1.132，该网段下面又连接了扩展路由器，192.168.1.x，client为192.168.1.100
         */
//        opcClient.asyncReadObject("TEST.FB", 500);

        // 延迟
        delay(10 * 60 * 1000);
    }

    private static void delay(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
